﻿using System;
using System.Diagnostics;

namespace MikeKappel.Com.CS
{
    public static partial class SortingAlgorithms
    {
        public delegate Boolean BucketDelegate(Int32 currentIndex, Int32 currentValue);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="onSort">On value change method to fire</param>
        /// <param name="ittems">Array of Integers to sort</param>
        public static void BucketSort(Int32[] items, BucketDelegate onSort)
        {
            Int32[] buckets = new Int32[items.Length + 1];
            for (Int32 i = 0; i < items.Length; ++i)
            {
                if (onSort != null && !onSort(i, items[i]))
                    goto escape;

                ++buckets[items[i]];
            }
            for (Int32 i = 0, j = 0; j < buckets.Length; ++j)
                for (Int32 k = buckets[j]; k > 0; --k)
                {
                    if (onSort != null && !onSort(j, buckets[j]))
                            goto escape;

                    items[i++] = j;
                }

        escape:
            return;
        }
        public static void BucketSort(Int32[] items)
        {
            BucketSort(items, null);
        }
    }
}
